﻿package com.okwanshiwu.alarm;

import com.okwanshiwu.pojo.email.YeEmail;

import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件发送工具，用于对业务错误的报警
 *
 * @author master
 * @create 2017-08-01 15:57
 **/
public class EmailAlarm {

	/**
	 * 发送邮箱通知--邮件通知
	 *
	 * @author master
	 */
	public static void sendEmail(String receiver,String title,String content) throws Exception {
		YeEmail yeEmail = new YeEmail();
		yeEmail.setReceiver(receiver);
		yeEmail.setTitle(title);
		yeEmail.setContent(content);
		yeEmail.setSender("yuanzhen@okwanshiwu.com");
		Properties prop = new Properties();
		prop.setProperty("mail.host", "smtp.exmail.qq.com");
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");
		// 使用JavaMail发送邮件的5个步骤
		// 1、创建session
		Session session = Session.getInstance(prop);
		// 开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
		session.setDebug(true);
		// 2、通过session得到transport对象
		Transport ts = session.getTransport();
		// 3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
		ts.connect("smtp.exmail.qq.com", "yuanzhen@okwanshiwu.com", "Aa111111");
		// 4、创建邮件
		Message message = createSimpleMail(session, yeEmail);
		// 5、发送邮件
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();

	}

	private static MimeMessage createSimpleMail(Session session, YeEmail yeEmail) throws Exception {
		// 创建邮件对象
		MimeMessage message = new MimeMessage(session);
		// 指明邮件的发件人
		message.setFrom(new InternetAddress(yeEmail.getSender()));
		// 指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(yeEmail.getReceiver()));
		// 邮件的标题
		// message.setSubject("只包含文本的简单邮件");
		message.setSubject(yeEmail.getTitle());
		// 邮件的文本内容
		message.setContent(yeEmail.getContent(), "text/html;charset=UTF-8");
		// 返回创建好的邮件对象
		return message;
	}

}
